package com.gsafety.wellsfort.controller.mobile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gsafety.wellsfort.common.context.LoginContextUtil;
import com.gsafety.wellsfort.common.enums.RedisPrefixEnum;
import com.gsafety.wellsfort.common.util.ApiResponse;
import com.gsafety.wellsfort.common.util.ResultCode;
import com.gsafety.wellsfort.config.CacheManager;
import com.gsafety.wellsfort.dao.organization.StudentLoginRelDAO;
import com.gsafety.wellsfort.dao.security.UserLoginDAO;
import com.gsafety.wellsfort.domain.dto.PageQueryDTO;
import com.gsafety.wellsfort.domain.dto.course.*;
import com.gsafety.wellsfort.domain.dto.courseware.CoursewareStudyDTO;
import com.gsafety.wellsfort.domain.model.course.Course;
import com.gsafety.wellsfort.domain.model.knowledge.ExamPaper;
import com.gsafety.wellsfort.domain.model.organization.Student;
import com.gsafety.wellsfort.domain.model.organization.StudentLoginRel;
import com.gsafety.wellsfort.domain.model.pushRecord.PushInfoRecord;
import com.gsafety.wellsfort.domain.model.security.UserLogin;
import com.gsafety.wellsfort.domain.vo.*;
import com.gsafety.wellsfort.service.anyineng.AnYiNengService;
import com.gsafety.wellsfort.service.common.IPushService;
import com.gsafety.wellsfort.service.course.CourseService;
import com.gsafety.wellsfort.service.course.MyExamService;
import com.gsafety.wellsfort.service.course.MyWorkService;
import com.gsafety.wellsfort.service.knowledge.WorkService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

@Api(value = "学生手机端相关接口", description = "学生手机端相关接口")
@RestController
@Slf4j
@RequestMapping("/api/stu-m")
public class StuMobileController {

    @Autowired
    private CourseService courseService;

    @Autowired
    private MyWorkService myWorkService;

    @Autowired
    private MyExamService myExamService;

    @Autowired
    private WorkService workService;

    @Autowired
    private AnYiNengService anYiNengService;

    @Autowired
    private CacheManager cacheManager;

    @Autowired
    private IPushService pushService;

    @Autowired
    UserLoginDAO userLoginDAO;

    @Autowired
    StudentLoginRelDAO studentLoginRelDAO;


    @ApiOperation(value = "课程详情(包括课程介绍和课程内容)")
    @PostMapping("/detail-course")
    public ApiResponse<CourseDetailVO> courseDetail(@RequestBody CourseIdDTO idDTO) {
        //统计热门课时
        cacheManager.addHashKeyIncr(RedisPrefixEnum.COURSE_VISIT_COUNT_PREFIX.getPrefix(), String.valueOf(idDTO.getCourseId()));
        //学习人数统计
        cacheManager.incr(RedisPrefixEnum.COURSE_VISIT_COUNT_By_DATE_PREFIX.getPrefix());
        return courseService.getCourseDetail(idDTO.getCourseId());
    }

    @ApiOperation(value = "正在学习课程")
    @PostMapping("/study-course")
    public ApiResponse<CourseDetailVO> studyCourse() {
        //访问数量统计(首页必须调用的接口)
        cacheManager.incr(RedisPrefixEnum.VISIT_SYSTEM_COUNT.getPrefix());
        //活跃用户统计
        cacheManager.addListKey(RedisPrefixEnum.ACTIVE_VISIT_COUNT_By_DATE_PREFIX.getPrefix(), String.valueOf(LoginContextUtil.getUid()));
        return courseService.getStudyCourse();
    }

    @ApiOperation(value = "课程推荐列表")
    @PostMapping("/course-list")
    public ApiResponse<List<MyCourseListVO>> recommendCourseList(@RequestBody PageQueryDTO pageQueryDTO) {
        return courseService.recommendCourseList(pageQueryDTO);
    }

    @ApiOperation(value = "查询手机端首页作业列表")
    @PostMapping("/work-list")
    public ApiResponse<List<MyWorkListVO>> workList(@RequestBody MyWorkDTO queryParams) {
        queryParams.setFinishState(null);
        return myWorkService.myWorkList(queryParams);
    }

    @ApiOperation(value = "查询手机端首页考试列表")
    @PostMapping("/exam-list")
    public ApiResponse<List<MyExamListVO>> examList(@RequestBody MyExamDTO queryParams) {
        queryParams.setFinishState(null);
        return myExamService.myExamList(queryParams);
    }

    @ApiOperation(value = "获取课时详情")
    @PostMapping("/detail-lessonPeriod")
    public ApiResponse<LessonPeriodVO> getLessonPeriod(@RequestBody LessonPeriodDetailDTO lessonPeriodDetailDTO) {
        return courseService.getLessonPeriod(lessonPeriodDetailDTO);
    }


    @ApiOperation(value = "我的课程列表")
    @PostMapping("/my-courseList")
    public ApiResponse<List<MyCourseListVO>> myCourseList(@RequestBody MyCourseDTO queryParams) {
        return courseService.myCourseList(queryParams);
    }

    @ApiOperation(value = "我的作业列表")
    @PostMapping("/my-workList")
    public ApiResponse<List<MyWorkListVO>> myWorkList(@RequestBody MyWorkDTO queryParams) {
        return myWorkService.myWorkList(queryParams);
    }

    @ApiOperation(value = "作业封面/详情")
    @PostMapping("/my-workDetail")
    public ApiResponse<MyWorkDetailVO> myWorkDetail(@RequestBody MyWorkDTO queryParams) {
        return myWorkService.myWorkDetail(queryParams);
    }

    @ApiOperation(value = "作业答题列表及解析")
    @PostMapping("/my-workQuList")
    public ApiResponse<List<MyQuestionVO>> myWorkQuestionList(@RequestBody MyWorkDTO queryParams) {
        return myWorkService.myWorkQuestionList(queryParams);
    }

    @ApiOperation(value = "提交作业答题卡")
    @PostMapping("/submit-workQuAnswer")
    public ApiResponse<WorkAnswerSheetDTO> submitWorkQuAnswer(@RequestBody WorkAnswerSheetDTO workAnswerSheetDTO) {
        return myWorkService.submitWorkQuAnswer(workAnswerSheetDTO);
    }

    @ApiOperation(value = "我的考试列表")
    @PostMapping("/my-examList")
    public ApiResponse<List<MyExamListVO>> myExamList(@RequestBody MyExamDTO queryParams) {
        return myExamService.myExamList(queryParams);
    }

    @ApiOperation(value = "考试封面/详情")
    @PostMapping("/my-examDetail")
    public ApiResponse<MyExamDetailVO> myWorkDetail(@RequestBody MyExamDTO queryParams) {
        return myExamService.myExamDetail(queryParams);
    }

    @ApiOperation(value = "考试答题列表")
    @PostMapping("/my-examQuList")
    public ApiResponse<List<MyQuestionVO>> myWorkQuestionList(@RequestBody MyExamDTO queryParams) {
        return myExamService.myExamQuestionList(queryParams);
    }

    @ApiOperation(value = "提交考试答题卡")
    @PostMapping("/submit-examQuAnswer")
    public ApiResponse<ExamAnswerSheetDTO> submitWorkQuAnswer(@RequestBody ExamAnswerSheetDTO examAnswerSheetDTO) {
        return myExamService.submitExamQuAnswer(examAnswerSheetDTO);
    }

    @ApiOperation(value = "我的安意能")
    @PostMapping("/my-anyineng")
    public ApiResponse<AnYiNengVO> myAnYiNeng() {
        return anYiNengService.myAnYiNeng();
    }

    @ApiOperation(value = "我的安意能详情")
    @PostMapping("/my-anyinengDetail")
    public ApiResponse<AnYiNengVO> myAnYiNengDetail(@RequestBody PageQueryDTO pageQueryDTO) {
        return anYiNengService.myAnYiNengDetail(pageQueryDTO);
    }

    @ApiOperation(value = "安意能考试答题列表")
    @PostMapping("/anyineng-examQuList")
    public ApiResponse<List<MyQuestionVO>> myAnYiNeng(@RequestBody MyExamDTO queryParams) {
        ExamPaper anyinengPaper = anYiNengService.getAnYiNengExamPapaer().getData();
        if (anyinengPaper != null) {
            queryParams.setExamId(anyinengPaper.getId());
            queryParams.setExamPublishId(-1);
            queryParams.setIfViewAnalysis(0);
            Integer studentId = LoginContextUtil.getStudent().getId();
            queryParams.setStudentId(studentId);
        } else {
            return ApiResponse.error(ResultCode.ERROR, "暂无安意能答题试卷");
        }

        return myExamService.myExamQuestionList(queryParams);
    }

    @ApiOperation(value = "课程列表")
    @PostMapping("/course/list")
    public ApiResponse<Set<Course>> courseList(@RequestBody IndexQueryVO indexQueryVO) {
        ApiResponse<Set<Course>> apiResponse = courseService.selectCourseByParam(indexQueryVO);
        Set<Course> set = apiResponse.getData();
        List<Course> list = new ArrayList<>();
        int startIndex = indexQueryVO.getStartIndex();
        if (set != null) {
            Iterator<Course> iterator = set.iterator();
            int i = 0;
            while (iterator.hasNext()) {
                Course course = iterator.next();
                if (i >= startIndex && i <= startIndex + indexQueryVO.getPageSize()) {
                    list.add(course);
                }
                i++;
            }
        }
        return ApiResponse.success(list, set.size());
    }

    @ApiOperation(value = "作业列表")
    @PostMapping("/work/list")
    public ApiResponse<Set<IndexWorkVO>> workList(@RequestBody IndexQueryVO indexQueryVO) {
        ApiResponse<Set<IndexWorkVO>> apiResponse = workService.selectWorkByParam(indexQueryVO);
        Set<IndexWorkVO> set = apiResponse.getData();
        List<IndexWorkVO> list = new ArrayList<>();
        int startIndex = indexQueryVO.getStartIndex();
        if (set != null) {
            Iterator<IndexWorkVO> iterator = set.iterator();
            int i = 0;
            while (iterator.hasNext()) {
                IndexWorkVO work = iterator.next();
                if (i >= startIndex && i <= startIndex + indexQueryVO.getPageSize()) {
                    list.add(work);
                }
                i++;
            }
        }
        return ApiResponse.success(list, set.size());
    }

    @ApiOperation(value = "考试列表")
    @PostMapping("/exam/list")
    public ApiResponse<Set<IndexExamVO>> examList(@RequestBody IndexQueryVO indexQueryVO) {
        ApiResponse<Set<IndexExamVO>> apiResponse = myExamService.selectExamByParam(indexQueryVO);
        Set<IndexExamVO> set = apiResponse.getData();
        List<IndexExamVO> list = new ArrayList<>();
        int startIndex = indexQueryVO.getStartIndex();
        if (set != null) {
            Iterator<IndexExamVO> iterator = set.iterator();
            int i = 0;
            while (iterator.hasNext()) {
                IndexExamVO exam = iterator.next();
                if (i >= startIndex && i <= startIndex + indexQueryVO.getPageSize()) {
                    list.add(exam);
                }
                i++;
            }
        }
        return ApiResponse.success(list, set.size());
    }


    @ApiOperation(value = "考试列表")
    @PostMapping("/index/search")
    public ApiResponse<Object> search(@RequestBody IndexQueryVO indexQueryVO) {
        JSONObject jsonObject = new JSONObject();
        ApiResponse<Set<Course>> courseApiResponse = courseService.selectCourseByParam(indexQueryVO);
        ApiResponse<Set<IndexWorkVO>> workApiResponse = workService.selectWorkByParam(indexQueryVO);
        ApiResponse<Set<IndexExamVO>> examApiResponse = myExamService.selectExamByParam(indexQueryVO);
        jsonObject.put("courseList", courseApiResponse.getData());
        jsonObject.put("workList", workApiResponse.getData());
        jsonObject.put("examList", examApiResponse.getData());
        return ApiResponse.success(jsonObject);
    }


    @ApiOperation(value = "获取课件学习时长")
    @PostMapping("/course/getCourseWareStudyTime")
    public ApiResponse<Object> getCourseWareStudyTime(@RequestBody CoursewareStudyDTO coursewareStudyDTO) {
        return courseService.getCourseWareStudyTime(coursewareStudyDTO);
    }

    @ApiOperation(value = "获取课件学习时长")
    @PostMapping("/course/updateCourseWareStudyTime")
    public ApiResponse<Object> updateCourseWareStudyTime(@RequestBody CoursewareStudyDTO coursewareStudyDTO) {
        return courseService.updateCourseWareStudyTime(coursewareStudyDTO);
    }

    @PostMapping("/pushRecord/list")
    @ApiOperation(value = "我的消息记录列表")
    public ApiResponse getList(@RequestBody QueryVO queryVO) {
        try {
            Student student = LoginContextUtil.getStudent();
            log.info("推送记录接口学生信息={}", JSON.toJSONString(student));
            List<StudentLoginRel> loginRels = studentLoginRelDAO.selectByStudentId(student.getId());
            if (CollectionUtils.isEmpty(loginRels)) {
                return ApiResponse.success("请使用正确用户信息");
            }
            Page page = PageHelper.startPage(queryVO.getPageNo(), queryVO.getPageSize());
            List<PushInfoRecord> list = pushService.getRecord(loginRels.get(0).getLoginId());
            if (CollectionUtils.isEmpty(list)) {
                return ApiResponse.success("未查询到消息记录");
            }
            PageInfo pageInfo = new PageInfo(page);
            pageInfo.setList(list);
            return ApiResponse.success(list, list.size());
        } catch (Exception e) {
            log.error("我的消息记录列表异常={}", e);
        }
        return ApiResponse.error();
    }
}
